<template>
  <div class="user">
    <el-card class="searchCard">
      <el-form>
        <el-form-item label="用户名：">
          <el-input v-model="userInput" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px;">
      <el-button type="primary" @click="addUserRole">添加用户</el-button>
      <el-button type="danger" :disabled="selectIdArr.length ? false : true" @click="deleteUserRole">批量删除</el-button>
      <el-table border style="margin: 20px 0px" :data="userRoleTable" @selection-change="selectChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="#" align="center" type="index"></el-table-column>
        <el-table-column label="id" align="center" prop="id"></el-table-column>
        <el-table-column label="用户名字" prop="username" show-overflow-tooltip></el-table-column>
        <el-table-column label="用户名称" prop="name" show-overflow-tooltip></el-table-column>
        <el-table-column label="用户角色" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button type="primary" size="small" icon="Edit" @click="editRole(row)">编辑</el-button>
            <el-popconfirm :title="`你确定要删除${row.username}?`" width="260px" @confirm="deleteUser(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]" small
        background layout="total, sizes, prev, pager, next, jumper" :total="totlaUserRole"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      <el-drawer v-model="showDrawer" direction="rtl" size="40%">
        <template #header>
          <h4>{{ userParams.id ? '编辑用户信息' : '添加用户信息' }} </h4>
        </template>
        <template #default>
          <el-form :model="userParams" ref="userForm" :rules="userRule">
            <el-form-item label="用户姓名" prop="username">
              <el-input placeholder="请填写用户名字" v-model="userParams.username"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="name">
              <el-input placeholder="请填写用户昵称" v-model="userParams.name"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
              <el-input placeholder="请填写用户密码" v-model="userParams.password"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleSure">确定</el-button>
        </template>
      </el-drawer>
      <el-drawer v-model="showDrawer2" direction="rtl" size="40%">
        <template #header>
          <h4>分配角色 </h4>
        </template>
        <template #default>
          <el-from>
            <el-form-item label="用户姓名">
              <el-input v-model="userParams.username" disabled></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                全部
              </el-checkbox>
              <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                <el-checkbox v-for="(role, index) in allRole" :key="role.id" :value="role">
                  {{ role.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-from>
        </template>
        <template #footer>
          <el-button @click="cancelRole">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref } from 'vue'
import {
  getAllUser,
  addOrUpdateUserInfo,
  deleteUserAPI,
  getAllRoles,
  saveUserRole,
  batchRemoveUser
} from '@/api/acl/user/index.ts'
import type { User } from '@/api/acl/user/type.ts'
import { ElMessage } from 'element-plus'
// 用户名输入框绑定的值
let userInput = ref('')
// 当前的页码
let pageNo = ref(1)
// 每页的条目数
let pageSize = ref(10)
// 用户信息列表总条目数
let totlaUserRole = ref(0)
// 用户信息table表格数据
let userRoleTable = ref([])
// 添加或编辑模式下的抽屉显示变量
let showDrawer = ref<boolean>(false)
// 分配角色的抽屉弹窗
let showDrawer2 = ref<boolean>(false)
//收集用户信息的响应式数据
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<User[]>([]);
// 获取当前新建和编辑用户的form表单，用于对输入框进行必要的校验
let userForm = ref()
//存储全部职位的数据
let allRole = ref([]);
//当前用户已有的职位
let checkedRoles = ref([]);
// 是否选中全部角色
const checkAll = ref(false)
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
// 自定义username的校验规则
const validatorUsername = (rule: any, value: any, callBack: any) => {
  if (value.trim().length < 5) {
    callBack(new Error('用户姓名至少5位'))
  } else {
    callBack()
  }
}
// 自定义name的校验规则
const validatorname = (rule: any, value: any, callBack: any) => {
  if (value.trim().length < 5) {
    callBack(new Error('用户昵称至少为5位'))
  } else {
    callBack()
  }
}
// 自定义password的校验规则
const validatorPassword = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack();
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
const userRule = {
  // 自定义校验规则
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

// 查看当前已有用户信息列表
const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  // 调用接口获取数据
  let result = await getAllUser(pageNo.value, pageSize.value, userInput.value)
  const { code, data } = result
  if (code == 200) {
    console.log(data, 'data')
    ElMessage.success('查询用户列表成功')
    userRoleTable.value = data.records
    totlaUserRole.value = data.total
  } else {
    ElMessage.error('查询用户列表失败')
  }
}
// 搜索按钮点击事件
const search = () => {
  console.log('search')
  getHasUser()
}
// 重置按钮点击事件
const reset = () => {
  // 清空输入框数据
  userInput.value = ''
  getHasUser()
}
// 添加用户角色信息
const addUserRole = () => {
  showDrawer.value = true
  //清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  // 清空上一次的校验信息
  userForm.value.clearValidate('username')
  userForm.value.clearValidate('name')
  userForm.value.clearValidate('password')
}
// 批量删除用户角色信息
const deleteUserRole = async () => {
  console.log('delete')
  let idsList = selectIdArr.value.map(item => {
    return item.id
  })
  let result = await batchRemoveUser(idsList)
  const { code } = result
  if (code == 200) {
    ElMessage.success('批量删除用户信息成功')
  } else {
    ElMessage.error('批量删除用户信息失败')
  }
  // 重新获取列表页数据
  getHasUser()
}
// 表格复选框点击事件
const selectChange = (val: any) => {
  console.log(val);
  selectIdArr.value = val


}
// 分配角色按钮点击事件
const setRole = async (row: any) => {
  console.log(row, 'row')
  userParams.id = row.id
  let result = await getAllRoles(row.id)
  const { code, data } = result
  if (code == 200) {
    userParams.username = row.name
    allRole.value = data.allRolesList
    checkedRoles.value = data.assignRoles
  } else {
    ElMessage.error('查询所有角色信息失败')
  }
  showDrawer2.value = true

}
// 编辑角色按钮点击事件
const editRole = (row: any) => {
  console.log(row, 'row')
  showDrawer.value = true
  userParams.id = row.id
  userParams.username = row.username
  userParams.name = row.name
  userParams.password = row.password
}
// 删除角色点击事件
const deleteUser = async (userId: number) => {
  let result = await deleteUserAPI(userId)
  const { code, data } = result
  if (code == 200) {
    ElMessage.success('删除用户成功')
    getHasUser()
  } else {
    ElMessage.error('删除用户失败')
  }
}
// 改变每页条目数
const handleSizeChange = () => {
  console.log('改变每页条目数')
  getHasUser()
}
// 翻页按钮点击事件
const handleCurrentChange = () => {
  console.log('翻页')
  getHasUser(pageNo.value)
}
// 添加用户角色的取消按钮点击事件
const cancel = () => {
  console.log('cancel')
  showDrawer.value = false
}
// 添加用户角色的确定按钮点击事件
const handleSure = async () => {
  // 首先校验表单是否合法，如果合法，那么调用接口保存用户信息，否则不允许提交
  if (!userForm) return
  userForm.value.validate(async (valid: any) => {
    if (valid) {
      // 调用接口，保存当前用户信息
      let result = await addOrUpdateUserInfo(userParams)
      const { code } = result
      if (code == 200) {
        ElMessage.success(userParams.id ? '更新用户信息成功' : '新建用户信息成功')
        showDrawer.value = false
        // 刷新页面，如果修改的用户是当前登录用户的话，那么刷新页面路由拦截器会监听到当前用户身份错误，那么就会退出登录
        window.location.reload()
        // 重新获取列表页数据
        getHasUser()
      } else {
        ElMessage.error(userParams.id ? '更新用户信息失败' : '新建用户信息失败')
      }
    }
  })
}
// 分配角色全选点击事件
const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 分配角色
const handleCheckedRolesChange = (val: string[]) => {
  checkAll.value = val.length == allRole.value.length
  isIndeterminate.value = val.length > 0 && val.length < allRole.value.length
}
// 分配角色弹窗的确定事件
const saveRole = async () => {
  console.log(checkedRoles.value);
  let obj = {
    roleIdList: checkedRoles.value.map(role => {
      return role.id
    }),
    userId: userParams.id
  }
  console.log(userParams.id);
  let result = await saveUserRole(obj)
  const { code } = result
  if (code == 200) {
    ElMessage.success('修改用户角色成功')
  } else {
    ElMessage.error('修改用户角色失败')
  }
  showDrawer2.value = false
  // 重新调用列表接口，获取列表页数据
  getHasUser()

}
// 分配角色弹窗的取消事件
const cancelRole = () => {
  showDrawer2.value = false

}
onMounted(() => {
  console.log('mounted');
  getHasUser()
})
</script>
<style lang="scss" scoped>
.el-input {
  width: 200px;
}

.searchCard {
  .el-form {
    display: flex;
    justify-content: space-between;
  }
}
</style>
